﻿// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. 
// See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics.Tracing;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Actors;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ActorAnalyzer
{
    public partial class MainForm : Form
    {
        internal static string s_defaultConnectionString = "127.0.0.1:19000";
        //private FabricActorClient m_client = null;
        //private TreeNodeCollection m_eventRoot = null;
        internal static EventLevel? ETWEventLevel;

        public MainForm()
        {
            InitializeComponent();
            textBoxFabricAddress.Text = s_defaultConnectionString;

            timer1.Interval = 1000;
            timer1.Tick += timer1_Tick;
            timer1.Start();
            
            //m_eventRoot = treeViewEvents.Nodes;
        }

        void timer1_Tick(object sender, EventArgs e)
        {
            var utcTime = DateTime.UtcNow;
            labelUtcTime.Text = utcTime.ToString("hh:mm:ss");
            //throw new NotImplementedException();
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            var connectionString = textBoxFabricAddress.Text;
            var chooser = new ActorChooser(connectionString);
            chooser.ShowDialog();
            if (chooser.ChosenUri == null) return;


            var isLocal = connectionString.Contains("localhost") || connectionString.Contains("127");

            // We'll add a new tab by creating a generic tab and adding our ActorTabPageControl to it.
            var actorTabPageControl = new ActorTabPageControl(connectionString, chooser.ChosenUri, chooser.ChosenPartitionName, !isLocal);
            string shortUriName = chooser.ChosenUri.ToString();
            if (shortUriName.StartsWith("fabric:/"))
                shortUriName = shortUriName.Substring(8);
            string title = shortUriName + ((chooser.ChosenPartitionName != null) ? ", "+chooser.ChosenPartitionName : String.Empty);
            var actorTab = new TabPage(title);
            actorTab.Margin = new Padding(0);
            actorTab.Padding = new Padding(0);
            actorTab.Controls.Add(actorTabPageControl);
            actorTabPageControl.Location = new Point(0, 0);
            actorTabPageControl.Dock = DockStyle.Fill;
            actorTabPageControl.SendToBack(); // just for safety, though with a single control it shouldn't matter
            tabControl1.TabPages.Add(actorTab);
        }

        private void etwLevelComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            ETWEventLevel = (EventLevel) etwLevelComboBox.SelectedIndex;

            foreach (TabPage tab in tabControl1.TabPages)
                foreach (ActorTabPageControl tabPage in tab.Controls)
                    tabPage.ChangeEventLevel(ETWEventLevel.Value);
        }

        protected override void OnClosing(CancelEventArgs e)
        {            
            // Unsubscribe from the event subscription.  But, don't block shutting down the app for more 
            // than a few seconds.
            List<Task> tasks = new List<Task>();
            foreach (TabPage tab in tabControl1.TabPages)
            {
                foreach (ActorTabPageControl tabPage in tab.Controls)
                {
                    Task t = new Task(() => tabPage.Unsubscribe());
                    t.Start();
                    tasks.Add(t);
                }
            }

            // Give these tasks a chance to complete, then shutdown anyways.
            if (tasks.Count > 0)
                Task.WaitAll(tasks.ToArray(), 6000);

            base.OnClosing(e);
        }
    }


}
